import { API_CONFIG } from "../../config"
import API, { request } from "../../plugins/api"
import base64 from "../../utils/base64.min"
import {
	aesMinEncrypt,
	aesDecrypt,
	loginAesMinEncrypt,
	requestSubscribeMessage,
} from "../../utils/util"
import { keyStack } from "../../utils/loginType"
import store from "../../store/index"

const app = getApp()
const ZXS = "在校生"
const BYS = "毕业生"
let showTemplaceId = false
let tmplIds
let schoolCode = ""
let timer = null

Page({
	data: {
		ZXS,
		BYS,
		showLeft: false,
		schoolCode: "",
		schoolName: "",
		userId: "",
		roleId: "", // 身份类型
		password: "",
		schoolList: [],
		showSchoolList: false,
		config: API_CONFIG,
		code: "",
		fileSwitch: false,
		notaryAgent: false,
		openPageList: [],
		openPageLoading: false,
		// projectList: [], // 出国留学项目列表
		isGd: false,
		pickerIndex: "",
		pickerArray: ["在校生", "毕业生"],

		gd_name: "", // 广大毕业生姓名
		gd_userId: "", // 广大毕业生学院
		phone: "", // 广大毕业生手机号
		cardNumber: "", // 广大毕业生身份证号
		// gd_name: "陈海兰", // 广大毕业生姓名
		// gd_userId: "1231456", // 广大毕业生学号
		// phone: "17674601897", // 广大毕业生手机号
		// cardNumber: "441522199207082146", // 广大毕业生身份证号

		phoneCode: "", // 广大毕业生短信验证码
		gd_code: "", // 广大毕业生图形验证码
		imageCode: "", // 图形验证码图片
		downNumber: 120, // 发送短信验证码的间隔
		MAX_NUMBER: 120,
		param2: "", //默认密码提示语
		param3: "", //是否开启图形验证码校验 ON 开启 OFF 关闭
		param4: "", // 登录页其它提示语
		MedicalOrNot: false, //重庆医科大学
	},
	onLoad(options = {}) {
		console.log(options, "login options")
		wx.removeStorageSync("changePwdStatus")
		const {
			dlhsdxCode, // 大连海事大学code
			isLogin,
			toggleLeft,
		} = options
		this.setData({
			showLeft: !isLogin,
		})
		if (toggleLeft === "login") {
			this.toggleLeft()
		}
		const code = wx.getStorageSync("dlhsdxCode")
		const institutionCode = wx.getStorageSync("InstitutionCode")
		// 南宁学院
		if (code && institutionCode) {
			this.setData({
				schoolCode: institutionCode,
			})
			this.dlhsLogin(code)
		}
		if (dlhsdxCode) {
			this.dlhsLogin(dlhsdxCode)
		}
		// 获取学校列表
		this.getSchoolList().then(() => {
			// 通过缓存回显已选的学校
			const userLoginCache = wx.getStorageSync("userLoginCache")
			if (userLoginCache) {
				let schoolItem
				let breakLoop = false // 设置标志变量
				for (let schoolListElement of this.data.schoolList) {
					if (breakLoop) {
						// 检查标志变量
						break // 如果标志变量为真，结束外层循环
					}
					for (let listElement of schoolListElement.list) {
						if (
							listElement.schoolCode.toString() ===
							userLoginCache.schoolCode.toString()
						) {
							schoolItem = listElement
							breakLoop = true // 当满足条件时，设置标志变量为真
							break // 结束内层循环
						}
					}
				}
				if (schoolItem) {
					this.fillLoginInfo(schoolItem)
				}
			}
		})
		if (app.globalData.extraData && app.globalData.extraData.userId) {
			this.otherFun()
		}
		if (app.globalData.corpCode && app.globalData.corpId) {
			this.qyH5Login()
		}
		if (app.globalData.autoQyLogin) {
			this.qyLogin().then((code) => {
				this.qyLoginFun(code)
			})
		}
		this.refreshFileSwitch()
		this.refreshOpenPageList()
		// this.refreshProjectList()
		wx.removeStorage({ key: "prevPopupTime" })
		wx.removeStorage({ key: "sqjnts" })
		this.tiktokUrlScheme()
		this.wzxyOpen()
		this.getImageCode()
	},
	onShow() {
		app.globalData.from = ""
		wx.hideHomeButton()
	},
	onUnload() {
		clearInterval(timer)
	},
	// 打开公众号文章
	// openArticle() {
	// 	wx.navigateTo({
	// 		url: `/pages/web/web?path=${encodeURIComponent(
	// 			"https://mp.weixin.qq.com/s/gddLe-G58KdzLmjx1parDw",
	// 		)}`,
	// 	})
	// },
	// 发送短信验证码
	sendSmsCode() {
		const { gd_code, gd_userId, gd_name, cardNumber, phone, schoolCode } =
			this.data
		if (!gd_code || !gd_userId || !gd_name || !cardNumber || !phone) {
			wx.showToast({
				title: "请填全信息",
				icon: "none",
				duration: 2000,
			})
			return
		}
		const reg = /^(?:(?:\+|00)86)?1\d{10}$/
		if (!reg.test(phone)) {
			wx.showToast({
				title: "手机号不符合格式",
				icon: "none",
				duration: 2000,
			})
			return
		}
		wx.showLoading({ title: "正在发送短信..." })
		wx.$API["login/sendPhoneCode"]({
			code: gd_code,
			name: gd_name,
			userId: gd_userId,
			phone,
			cardNumber,
			schoolCode,
		})
			.then((res) => {
				wx.hideLoading()
				wx.showToast({
					title: "短信已发送到手机,请注意查收",
					icon: "none",
					duration: 2000,
				})
				clearInterval(timer)
				timer = setInterval(() => {
					if (this.data.downNumber <= 0) {
						clearInterval(timer)
						this.setData({
							downNumber: this.data.MAX_NUMBER,
						})
						return
					}
					this.setData({
						downNumber: this.data.downNumber - 1,
					})
				}, 1000)
				console.log(res, "发送短信成功")
				this.getImageCode()
			})
			.catch((error) => {
				wx.hideLoading()
				console.log(error, "error")
				this.getImageCode()
				wx.showToast({
					title: error,
					icon: "none",
					duration: 2000,
				})
			})
	},
	// 获取图形验证码
	getImageCode() {
		wx.request({
			url:
				(API_CONFIG.isDev ? API_CONFIG.devUrl : API_CONFIG.productionUrl) +
				"openPage/getImageCode",
			method: "post",
			responseType: "arraybuffer",
			success: (res) => {
				let url = "data:image/png;base64," + wx.arrayBufferToBase64(res.data)
				console.log(res, "获取图片", url)
				this.setData({
					imageCode: url,
				})
			},
			fail: (error) => {
				console.log(error, "获取图形验证码失败")
			},
		})
	},
	bindPickerChange: function (e) {
		console.log("picker发送选择改变，携带值为", e.detail.value, schoolCode)

		this.setData({
			pickerIndex: e.detail.value,
			roleId: this.data.pickerArray[e.detail.value],
		})
		//重庆医科大学
		if (schoolCode == "4150010631" && e.detail.value == 0) {
			return this.setData({
				MedicalOrNot: true,
			})
		} else {
			return this.setData({
				MedicalOrNot: false,
			})
		}
		// 在校生
		if (this.data.pickerArray[this.data.pickerIndex] === ZXS) {
			const unifiedAuthUrl = wx.getStorageSync("unifiedAuthUrl")
			if (unifiedAuthUrl) {
				wx.navigateTo({
					url:
						"/pages/certification/certification?path=" +
						encodeURIComponent(unifiedAuthUrl),
				})
				return
			}
		} else {
			console.log("选中毕业生")
		}
	},
	viewAll() {
		wx.navigateTo({
			url: "/pages/web/web?path=https://xwx.gzzmedu.com/study_abroad/home",
		})
	},
	// 点击出国留学项目
	// openLook(e) {
	// 	const { index } = e.currentTarget.dataset
	// 	const item = this.data.projectList[index]
	// 	wx.navigateTo({
	// 		url: `/pages/web/web?path=${encodeURIComponent(
	// 			item.path,
	// 		)}&expanderCode=1674349987086995457`,
	// 	})
	// },
	// 获取出国留学项目列表
	// refreshProjectList() {
	// 	wx.request({
	// 		url: "https://xwx.gzzmedu.com:10086/enrollmentClient/getProjectPage",
	// 		method: "POST",
	// 		dataType: "json",
	// 		data: {}, // 必须有,不然数据异常
	// 		success: (res) => {
	// 			console.log(res, "获取响应的内容")
	// 			if (res.data.errcode === "0") {
	// 				res.data.result.data.forEach((item) => {
	// 					item.path = `https://xwx.gzzmedu.com/study_abroad/home/Details?id=${item.projectId}&expanderCode=1674349987086995457`
	// 				})
	// 				this.setData({
	// 					projectList: res.data.result.data,
	// 				})
	// 				console.log(this.data.projectList, "projectList")
	// 			} else {
	// 				wx.showToast({
	// 					title: res.data.errmsg,
	// 					icon: "none",
	// 				})
	// 			}
	// 		},
	// 		fail(error) {
	// 			console.log(error, "获取出国留学项目列表失败")
	// 		},
	// 	})
	// },
	// 企业自建应用 -> h5页面,h5页面网页授权获取到code,把code和企业id一块传到小程序 -> 小程序
	qyH5Login() {
		wx.showLoading({
			title: "正在登录...",
			mask: true,
		})
		wx.$API["login/login"]({
			loginType: 9,
			corpCode: app.globalData.corpCode,
			corpId: app.globalData.corpId,
		})
			.then((res) => {
				wx.hideLoading()
				app.globalData.corpCode = ""
				app.globalData.corpId = ""
				this.afterLogin(res)
				console.log("h5code带到小程序 登录成功了", res)
			})
			.catch((error) => {
				app.globalData.corpCode = ""
				app.globalData.corpId = ""
				wx.hideLoading()
				console.log(error, "error")
				wx.showToast({
					title: error,
					icon: "none",
					duration: 3000,
				})
			})
	},
	// 从缓存中读取开放页面列表
	async refreshOpenPageList() {
		this.setData({ openPageLoading: true })
		try {
			const openPageList = await store.getters.openPages()
			if (!openPageList.length) {
				this.setData({
					showLeft: false,
				})
			}
			const clicked = wx.getStorageSync("openPageClicked") || []
			openPageList.forEach((item) => {
				item.clicked = clicked.includes(item.id)
			})
			this.setData({
				openPageList: openPageList,
			})
			console.log(openPageList, "开放页面列表")
		} finally {
			this.setData({ openPageLoading: false })
		}

		// wx.$API["login/getOpenPageList"]()
		// 	.then((res) => {
		// 		if (!res.data.length) {
		// 			this.setData({
		// 				showLeft: false,
		// 			})
		// 		}
		// 		const clicked = wx.getStorageSync("openPageClicked") || []
		// 		res.data.forEach((item) => {
		// 			item.clicked = clicked.includes(item.id)
		// 		})
		// 		this.setData({
		// 			openPageList: res.data,
		// 			openPageLoading: false,
		// 		})
		// 		//缓存供其他页面使用
		// 		store.setters.setOpenPages(res.data)
		// 		console.log(res, "开放页面列表")
		// 	})
		// 	.catch((error) => {
		// 		this.setData({ openPageLoading: false })
		// 		console.log(error, "error")
		// 		wx.showToast({
		// 			title: error,
		// 			icon: "none",
		// 			duration: 3000,
		// 		})
		// 	})
	},
	onOpenNoLoginPage(e) {
		let config = e.currentTarget.dataset.query
		const index = e.currentTarget.dataset.index
		console.log(config, "config")
		//点击率统计
		request({
			url: "openPage/openPageClick",
			data: {
				openPageId: config.id,
				openPageTitle: config.title,
			},
			method: "post",
		})
		if (!config.requestUrl) {
			wx.showToast({
				title: "该项未配置跳转地址,请联系相关管理员配置",
				icon: "none",
			})
			return
		}
		//将该项标记为已点击过了（用于控制右上角小红点的展示）
		let clickedList = wx.getStorageSync("openPageClicked") || []
		if (!clickedList.includes(config.id)) {
			clickedList.push(config.id)
			wx.setStorageSync("openPageClicked", clickedList)
			this.setData({
				[`openPageList[${index}].clicked`]: true,
			})
		}
		if (config.appid) {
			wx.navigateToMiniProgram({
				appId: config.appid,
				path: config.requestUrl,
				envVersion: config.envVersion,
				extraData: {
					from: "xwx",
				},
			})
		} else if (/^http(s)?/.test(config.requestUrl)) {
			wx.navigateTo({
				url: `/pages/web/web?path=${encodeURIComponent(config.requestUrl)}`,
			})
		} else {
			wx.navigateTo({
				url: config.requestUrl,
			})
		}
	},
	toggleLeft() {
		//设置页面标题为 登录
		if (this.data.showLeft) {
			wx.setNavigationBarTitle({
				title: "登录",
			})
			//设置页面标题为首页
		} else {
			wx.setNavigationBarTitle({
				title: "首页",
			})
		}
		this.setData({
			showLeft: !this.data.showLeft,
		})
		const token = wx.getStorageSync("token")
		if (token) {
			// 效验token是否过期
			this.tokenVerify(token)
		}
	},
	/**
	 * @see token校验
	 * @param {token} String
	 */
	tokenVerify(token) {
		console.log("效验token是否过期", token)
		try {
			const tokenPlyload = base64.decode(token.split(".")[1])
			const tokenJson = JSON.parse(tokenPlyload)
			const currentTime = new Date().getTime()
			let { exp } = tokenJson
			exp = parseInt(exp + "000")
			if (exp - currentTime > 60 * 1000 * 50) {
				// if (exp - currentTime > 86400000 * 5) {
				// 86400000 * 5
				// token未过期（86400000为1天的时间戳，这个判断为每两天一刷）
				this.setData({
					userId: wx.getStorageSync("userInfo").userId,
				})
				this.againLogin()
				wx.hideLoading()
			}
		} catch (error) {
			wx.hideLoading()
			wx.showModal({
				title: "提示",
				content: "登录异常",
				showCancel: false,
			})
			wx.clearStorageSync()
			console.log("token错误", error, token)
		}
	},
	/**
	 * @see 重新登录
	 */
	againLogin() {
		wx.login({
			success: (res) => {
				const request = { code: res.code, loginType: 1 }
				console.log("访问登录接口", request)
				wx.$API["login/login"](request)
					.then((result) => {
						console.log("校验过了", result)
						const { token, data, schoolConfig } = result
						app.storageData(token, data[0], schoolConfig)
						// wx.hideLoading()

						wx.reLaunch({
							url: "/pages/home/index",
						})
					})
					.catch((err) => {})
			},
			fail: (err) => {
				// wx.hideLoading()
				wx.showModal({
					title: "提示",
					content: "获取code失败,请退出微信后重试",
					showCancel: false,
				})
			},
		})
	},
	wzxyOpen() {
		if (app.globalData.from === "WZXY" && app.globalData.app === "file") {
			console.log(
				"从[我在校园跳转过来]在[登录]页面进入文件代办",
				app.globalData.app,
			)
			wx.navigateTo({
				url: "/pages/web/web?path=https://xwx.gzzmedu.com/file-agency?from=WZXY",
				success() {
					app.globalData.from = ""
					app.globalData.app = ""
				},
			})
		}
	},
	tiktokUrlScheme() {
		if (app.globalData.from === "TikTokSms") {
			wx.navigateTo({
				url: "/pages/web/web?path=https://xwx.gzzmedu.com/advertising",
				success() {
					app.globalData.from = ""
				},
			})
			return
		}
	},
	refreshFileSwitch() {
		wx.$API["login/getAgencyEnable"]()
			.then((res) => {
				console.log(res, "获取文件代办开关")
				this.setData({
					fileSwitch: res.data[0],
				})
			})
			.catch((error) => {
				console.log(error, "error")
				wx.hideLoading()
				wx.showToast({
					title: error,
					icon: "none",
					duration: 3000,
				})
			})
	},
	fileAgency() {
		app.globalData.isHzdb = true
		wx.navigateTo({
			url: "/pages/web/web?path=https://xwx.gzzmedu.com/file-agency/",
			// url: '/pages/web/web?path=http://192.168.5.117:13915/file-agency',
		})
	},
	/**
	 * 公证
	 */
	notarization() {
		app.globalData.isHzdb = true
		wx.navigateTo({
			url: "/pages/notarization/notarization?path=http://192.168.7.76:13916/notary-agent/",
		})
	},
	goToQuestionnaire() {
		wx.navigateTo({
			// url: '/pages/questionnaire/index' // 调查问卷
			url: `/pages/person/help/help?page=login`, // 更多帮助
		})
	},
	tips() {
		wx.showModal({
			title: "提示",
			content:
				"本科生密码一般为身份证证后六位或教务系统密码或学校信息门户统一身份证登录账号和密码，研究生密码一般为身份证证后六位或研究生系统密码或学校信息门户统一身份证登录账号和密码。谢谢使用，如有问题可咨询客服！",
			confirmColor: "#2172ed",
			showCancel: false,
		})
	},
	/**
	 * @see 大连海事统一身份认证登录
	 */
	dlhsLogin(code) {
		const institutionCode = wx.getStorageSync("InstitutionCode")
		wx.login({
			success: (res) => {
				const request = {
					signature: code,
					loginType: 8, // 统一身份认证登录
					code: res.code,
					schoolCode: institutionCode || this.data.schoolCode,
				}
				console.log(
					"大连海事统一身份认证登录参数: ",
					request,
					this.data.schoolCode,
				)
				wx.showLoading({
					title: "正在登录...",
					mask: true,
				})
				wx.$API["login/login"](request)
					.then((result) => {
						wx.hideLoading()
						this.afterLogin(result)
					})
					.catch((error) => {
						wx.hideLoading()
						wx.showToast({
							title: error,
							icon: "none",
							duration: 3000,
						})
						console.log("登录失败", error)
						wx.setStorage({ key: "dlhsdxCode", data: "" })
						wx.setStorage({ key: "InstitutionCode", data: "" })
					})
			},
			fail: (err) => {
				wx.showModal({
					title: "提示",
					content: "获取code失败,请退出微信后重试",
					showCancel: false,
				})
			},
		})
	},
	/**
	 * @see 获取学校列表
	 */
	getSchoolList() {
		return new Promise((resolve, reject) => {
			wx.$API["login/getSchoolList"]({ type: 1 })
				.then((result) => {
					const { data } = result
					data.forEach((item) => {
						item.list.forEach((it) => {
							it.key = item.key
						})
					})
					this.setData({
						schoolList: data,
					})
					resolve()
				})
				.catch((err) => {
					wx.showToast({
						title: "获取学校列表失败",
						icon: "none",
						duration: 2000,
					})
					reject()
				})
		})
	},
	/**
	 * @see 企业微信登录
	 */
	qyLoginFun(code, signature) {
		const request = {
			code,
			loginType: 7,
		}
		if (signature) {
			request.signature = signature
		}
		console.log("企业微信登录参数", request, signature)
		wx.showLoading({
			title: "正在登录...",
			mask: true,
		})
		wx.$API["login/login"](request)
			.then((result) => {
				wx.hideLoading()
				if (result.signature) {
					// 如果需要重新传递code
					this.qyLogin().then((code) => {
						this.qyLoginFun(code, result.signature)
					})
				} else {
					this.afterLogin(result)
					console.log("登录成功", result)
				}
			})
			.catch((error) => {
				wx.hideLoading()
				wx.showToast({
					title: error,
					icon: "none",
					duration: 3000,
				})
				console.log("登录失败", error)
			})
	},
	/**
	 * @see 获取企业微信code
	 */
	qyLogin() {
		return new Promise((resolve, reject) => {
			wx.getSystemInfo({
				success(res) {
					if (res.environment === "wxwork") {
						resolve()
					}
					console.log(res, "获取小程序运行环境")
				},
			})
		}).then(() => {
			return new Promise((resolve, reject) => {
				if (wx.qy) {
					wx.qy.login({
						success: (res) => {
							if (res.code) {
								resolve(res.code)
							} else {
								reject(res)
							}
						},
						fail(error) {
							reject(error)
						},
					})
				}
			})
		})
	},
	/**
	 * @see 别的小程序跳转登录
	 * @param {微信code} code
	 */
	jumpLogin(code) {
		let { colleageCode, userId, schoolCode } = app.globalData.extraData
		// 如果 colleageCode 存在  提前找到对应的 schoolCode
		if (colleageCode) {
			schoolCode = keyStack[colleageCode].schoolCode
		}
		wx.showLoading({
			title: "正在登录...",
			mask: true,
		})
		wx.$API["login/getServiceTime"]()
			.then((res) => {
				return new Promise((resolve, reject) => {
					let { currentTime } = res
					let param = {
						schoolCode,
						userId,
						timeMillis: currentTime,
					}
					let signature = JSON.stringify(param)
					const request = {
						schoolCode,
						code,
						loginType: 6, // 登录类型
						signature: aesMinEncrypt(signature),
					}
					// console.log("加密对象  param", param, "请求参数", request)
					API["login/login"](request)
						.then((res) => {
							app.globalData.extraData = null
							wx.hideLoading()
							this.afterLogin(res)
							resolve()
						})
						.catch((error) => reject(error))
				})
			})
			.catch((error) => {
				wx.hideLoading()
				wx.showToast({
					title: error,
					icon: "none",
					duration: 2000,
				})
				showTemplaceId = false
			})
	},
	/**
	 * @see 别的小程序跳转登录
	 */
	otherFun() {
		wx.login({
			success: (res) => {
				this.jumpLogin(res.code)
			},
			fail: (err) => {
				wx.showModal({
					title: "提示",
					content: "获取code失败,请退出微信后重试",
					showCancel: false,
				})
			},
		})
	},
	/**
	 * @see 登录后对返回值统一处理
	 */
	afterLogin(result) {
		const { token, data, schoolConfig, code } = result
		app.storageData(token, data[0], schoolConfig, this.data.code)
		// wx.showLoading({ mask: true, title: '登录中' })
		// 重定向地址
		const redirect = app.globalData.redirect
		app.globalData.redirect = ""
		// wx.hideLoading()
		if (redirect) {
			wx.redirectTo({
				url: redirect,
			})
		} else {
			wx.reLaunch({
				url: "/pages/home/index",
			})
		}
	},
	// 广大登录
	gdLogin() {
		const { phone, phoneCode, schoolCode, cardNumber, gd_userId } = this.data
		// 校验参数是否完整
		if (!schoolCode || !phone || !phoneCode || !cardNumber || !gd_userId) {
			wx.showToast({
				title: "请填全信息",
				icon: "none",
				duration: 2000,
			})
			return
		}
		wx.login({
			success: (wx_code) => {
				wx.showLoading({
					title: "正在登录...",
				})
				wx.$API["login/login"]({
					code: wx_code.code,
					schoolCode,
					loginType: 10,
					phone,
					phoneCode,
					cardNumber,
					userId: gd_userId,
				})
					.then((res) => {
						wx.hideLoading()
						this.afterLogin(res)
					})
					.catch((error) => {
						console.log(error, "error")
						wx.hideLoading()
					})
			},
			fail: (error) => {
				console.log(error, "获取微信code失败")
				wx.showModal({
					title: "提示",
					content: "获取code失败,请退出微信后重试",
					showCancel: false,
				})
			},
		})
	},
	/**
	 * @see 登录
	 */
	login() {
		const {
			userId,
			password,
			gd_code,
			gd_userId,
			gd_name,
			phone,
			phoneCode,
			cardNumber,
		} = this.data
		if (schoolCode + "" === "4144011078") {
			// 广大
			if (this.data.pickerIndex === "0") {
				// 在校生
				const unifiedAuthUrl = wx.getStorageSync("unifiedAuthUrl")
				if (unifiedAuthUrl) {
					wx.navigateTo({
						url:
							"/pages/certification/certification?path=" +
							encodeURIComponent(unifiedAuthUrl),
					})
					return
				}
			} else {
				this.gdLogin()
			}
			return
			// 重庆医科大学
		} else if (schoolCode + "" === "4150010631") {
			if (this.data.pickerIndex === "1") {
				return this.gdLogin()
			}
		} else {
			const unifiedAuthUrl = wx.getStorageSync("unifiedAuthUrl")
			if (unifiedAuthUrl) {
				// 是统一身份认证
				wx.navigateTo({
					url:
						"/pages/certification/certification?path=" +
						encodeURIComponent(unifiedAuthUrl),
				})
				return
			}
		}
		if (!schoolCode || !userId || !password) {
			wx.showToast({
				title: "请填全信息",
				icon: "none",
				duration: 2000,
			})
			return
		}
		this._login()
	},
	_login() {
		const { userId, password, gd_code, gd_userId, gd_name, phone, phoneCode } =
			this.data
		wx.showLoading({
			mask: true,
			title: "正在获取模板消息",
		})
		if (!showTemplaceId) {
			try {
				API["home/getTemplateIds"]({ schoolCode })
					.then((result) => {
						const { data } = result
						tmplIds = data
						showTemplaceId = true
						this.login()
						wx.hideLoading()
					})
					.catch((err) => {
						wx.showToast({
							title: err,
							icon: "none",
						})
					})
			} catch (err) {
				wx.hideLoading()
				wx.showModal({
					title: "获取模板消息失败,是否重试?",
					content: "",
					success: (res) => {
						if (res.confirm) {
							showTemplaceId = false
						} else {
							showTemplaceId = true
						}
						this.login()
					},
				})
			}
		} else {
			wx.hideLoading()
			new Promise((resolve, reject) => {
				wx.requestSubscribeMessage({
					tmplIds: tmplIds.slice(0, 3),
					success: (res) => {
						requestSubscribeMessage()
						console.log(res, "调用成功")
					},
					fail: (err) => {
						console.log(err, "调用模板消息通知失败")
					},
					complete: () => {
						resolve()
					},
				})
			}).then(() => {
				wx.showLoading({
					mask: true,
					title: "登录中",
				})
				wx.login({
					success: (res) => {
						const params = {
							code: res.code,
							loginType: 2,
							schoolCode,
							userId: loginAesMinEncrypt(
								userId,
								"JL$<&*l9~67?:#5p",
								"{g;,9~l4'/sw`885",
							),
							password: loginAesMinEncrypt(
								password,
								"JL$<&*l9~67?:#5p",
								"{g;,9~l4'/sw`885",
							),
							imageCode: this.data.gd_code,
						}
						this.setData({
							code: res.code,
						})
						request({
							url: "api/login/user",
							data: params,
						})
							.then((result) => {
								this.afterLogin(result)
							})
							.catch((err) => {
								console.log(err, "err")
								wx.hideLoading()
								wx.showToast({
									title: err,
									icon: "none",
									duration: 2000,
								})
								showTemplaceId = false
								// 更换图形验证码
								this.getImageCode()
							})
					},
					fail: (err) => {
						wx.showModal({
							title: "提示",
							content: "获取code失败,请退出微信后重试",
							showCancel: false,
						})
					},
					complete: () => {
						wx.hideLoading()
					},
				})
			})
		}
	},
	/**
	 * @see 选择学校
	 */
	selectSchool(e) {
		const { schoolName, enable, param2, param3, param4 } =
			e.currentTarget.dataset.item
		const item = e.currentTarget.dataset.item
		console.log(item, "选择了学校")
		schoolCode = e.currentTarget.dataset.item.schoolCode
		if (enable === 0) {
			// 缓存选中的学校
			wx.setStorageSync("userLoginCache", item)
			// 将选中的学校展示在页面上
			this.setData(
				{
					schoolName,
					showSchoolList: false,
					schoolCode,
					param2: param2 ? param2 : "",
					param3: param3 ? param3 : "", // 是否开启图形验证码校验 ON 开启 OFF 关闭
					param4: param4 ? param4 : "", // 登录页其它提示语
				},
				() => {
					// 如果是广州大学
					if (e.currentTarget.dataset.item.schoolCode + "" === "4144011078") {
						// console.log("选中广州大学,需要选择登录身份")
						this.setData({
							isGd: true,
						})
						wx.setStorageSync(
							"unifiedAuthUrl",
							e.currentTarget.dataset.item.unifiedAuthUrl,
						)
						// wx.setStorageSync("userLoginCache", {
						// 	schoolName,
						// 	userId: "",
						// 	schoolCode: schoolCode,
						// })
						console.log("缓存schoolCode: " + schoolCode)
					} else if (
						e.currentTarget.dataset.item.schoolCode + "" ===
						"4150010631"
					) {
						//如果选择是的重庆医科大学
						this.setData({
							isGd: true,
							MedicalOrNot: false,
						})
					} else {
						this.setData({
							isGd: false,
						})
						// 检测到统一身份验证登录方式,缓存当前code后跳转
						if (e.currentTarget.dataset.item.unifiedAuthUrl) {
							wx.setStorageSync(
								"unifiedAuthUrl",
								e.currentTarget.dataset.item.unifiedAuthUrl,
							)
							wx.navigateTo({
								url:
									"/pages/certification/certification?path=" +
									encodeURIComponent(
										e.currentTarget.dataset.item.unifiedAuthUrl,
									),
							})
						} else if (e.currentTarget.dataset.item.schoolCode === 4161010701) {
							wx.navigateTo({
								url: "/pages/xAdzkjdx/index",
							})
						} else {
							wx.removeStorage({ key: "unifiedAuthUrl" })
						}
					}
				},
			)
		} else {
			wx.showModal({
				title: "提示",
				content: "暂未开放",
				complete: (res) => {
					schoolCode = ""
					this.setData({
						schoolName: "",
						showSchoolList: false,
					})
				},
			})
		}
	},
	/**
	 * @see 显示选择学校弹层
	 */
	showDrawer() {
		this.setData({
			showSchoolList: true,
		})
	},
	/**
	 * @see 输入框value修改方法
	 */
	bindKeyInput(e) {
		const { currentTarget, detail } = e
		this.setData({ [currentTarget.dataset.name]: detail.value })
	},
	/**
	 * @see 填充登录信息
	 * @param schoolItem
	 */
	fillLoginInfo(schoolItem) {
		schoolCode = schoolItem.schoolCode
		this.setData({
			// 是否是广州大学
			isGd:
				schoolCode + "" === "4144011078" || schoolCode + "" === "4150010631",
		})
		this.selectSchool({
			currentTarget: {
				dataset: {
					item: {
						...schoolItem,
						enable: 0,
					},
				},
			},
		})
		// this.setData({
		// 	schoolName,
		// 	userId,
		// 	schoolCode,
		// 	param2: userLoginCache.param2 ? userLoginCache.param2 : "",
		// 	param3: userLoginCache.param3 ? userLoginCache.param3 : "",
		// 	param4: userLoginCache.param4 ? userLoginCache.param4 : "",
		// })
	},
	close() {
		this.setData({
			showSchoolList: !this.data.showSchoolList,
		})
	},
	// 显示使用说明
	showMsg() {
		wx.showModal({
			title: "服务说明",
			content:
				"您将访问“校务行”小程序为您提供的校园办事服务和辅助学习服务，该小程序提供的服务为学校官方授权，数据均来源于学校服务器，该小程序不会以任何理由保存或使用您的数据；请确定您已知晓该小程序为您提供的服务与功能",
			confirmColor: "#2172ed",
			confirmText: "同意继续",
			showCancel: false,
		})
	},
	//跳转到 校务行需求收集表 问卷调查填写页面
	goToFillQuestionnaire() {
		wx.navigateTo({
			url:
				"/pages/web/web?path=" +
				encodeURIComponent(
					"https://xwx.gzzmedu.com/questionnaire1/?questionnaireId=7",
				),
		})
	},
	//跳转到站内页面
	goToPage(event) {
		const { url } = event.currentTarget.dataset
		wx.navigateTo({
			url: url,
		})
	},
	//跳转到h5页面
	goToH5(event) {
		const { url } = event.currentTarget.dataset
		wx.navigateTo({
			url: `/pages/web/web?path=${encodeURIComponent(url)}`,
		})
	},
	//跳转到别的小程序
	goToMiniProgram(event) {
		const { appid, path, envversion } = event.currentTarget.dataset
		wx.navigateToMiniProgram({
			appId: appid,
			path: path,
			envVersion: envversion,
		})
	},
})
